package org.NooLab.itexx.app.controller;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;

import org.NooLab.itexx.ITexxWindowCommons;
import org.NooLab.itexx.app.config.ITexxAppPropertiesIntf;
import org.NooLab.utilities.files.DFutils;
import org.NooLab.utilities.gui.SystemProperties;
import org.NooLab.utilities.resources.ResourceLoader;
import org.NooLab.utilities.strings.StringsUtil;

// import org.NooLab.itexx.ITexxWindowCommons;




public class PreferencesHandler {

	ITexxWindowCommons appCommons;
	ITexxAppPropertiesIntf appProperties;
	
	String appPath = "",preferencesFile="";
	
	DFutils fileutil = new DFutils();
	
	// ========================================================================
	public PreferencesHandler(ITexxWindowCommons _commons) {
		//
		appCommons = _commons;
		appProperties = appCommons .getAppProperties() ;
		
		appPath = appProperties.getOwnAppPath() ;
		
		preferencesFile = DFutils.createPath(appPath, "preferences.txt") ;
		if (DFutils.fileExists(preferencesFile)==false){
			checkForExport();
		}
	}
	// ========================================================================

	public PreferencesHandler checkForExport(){
	
		if (appPath.contains("/app/")){
			preferencesFile = DFutils.createPath(appPath, "preferences.txt") ;
			
			if (DFutils.fileExists(preferencesFile)==false){
				// DFutils.
				ResourceLoader rL = new ResourceLoader() ;
				boolean hb = rL.loadTextResource( appProperties.getClassOfMain(), 
												  ITexxAppPropertiesIntf._PREFS_RESOURCE_PATH );
				if (hb){
					String prefFileContent = rL.getTextResource();
					if (prefFileContent.length()>10){
						// if windows
						if (SystemProperties.operatingSystemName().toLowerCase().contains("win")){
							prefFileContent = StringsUtil.replaceall(prefFileContent, "|||", "\r\n");
						}else{
							prefFileContent = StringsUtil.replaceall(prefFileContent, "|||", "\n");
						}
						fileutil.writeFileSimple(preferencesFile,prefFileContent);
					}
				}
			} 
			
			
		}
		return this;
	}
	
	public PreferencesHandler openPreferencesView() throws IOException {
		// 

		if (DFutils.fileExists(preferencesFile) ){
			Desktop.getDesktop().open( new File(preferencesFile)) ;
		}
		return this;
	}
	
}
